package com.roc.web.action.agent;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.roc.bean.TermBean;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.Operators;
import com.roc.pojo.ProfitModule;
import com.roc.pojo.ProfitPercent;
import com.roc.pojo.ProfitRule;
import com.roc.service.IAgentService;
import com.roc.service.IMerchantServices;
import com.roc.service.IModelService;
import com.roc.service.IorgService;
import com.roc.service.ServiceException;
import com.roc.service.operator.IPowerInfoService;
import com.roc.util.Constance;
import com.roc.util.DateUtil;
import com.roc.util.Utils;
import com.roc.util.constant.AgentNumberType;
import com.roc.util.constant.ConfigProperties;
import com.roc.util.constant.Constant;
import com.roc.util.constant.InvoiceRateType;
import com.roc.util.constant.MerberFlag;
import com.roc.util.constant.ProfitModuleStatus;
import com.roc.util.constant.Role;
@Component
@Namespace("/oneAgent")
@SuppressWarnings("all")
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class OneAgentAction extends PaginationBaseAction{
	static Logger logger = Logger.getLogger(OneAgentAction.class);
	@Autowired
	IorgService orgService;
	@Autowired
	IAgentService  agentService;
	@Autowired
	IModelService modelService;
	@Autowired
	private IPowerInfoService operatorService;
	
	@Autowired 
	IMerchantServices merchantServices;

	@Autowired
	IPowerInfoService powerInfoService;
	
	private Operators agent;
	
	private List<ProfitPercent> profitPerList;
	//代理申请
	@Action(value = "addOneAgent", results = {
			@Result(name = "success",type="chain", location = "oneAgentJsp"),
			@Result(name = "error", location = "/error.jsp") }
	)
	public String  addOneAgent(){
		Operators logingOperators=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);

		String pwd = "";
		try {
			String loginId = String.valueOf(logingOperators.getId());
			// 如果登陆账号不是系统管理员以及收单事业部
			if( !logingOperators.getRoleType().equals(Role.SYSTEM.getCode())
					 && !loginId.equals(Constant.SHOUDANSHIYEBU_ID)){
				addActionError("此登陆账号没有权限");
				return ERROR;
			}

			if( !Utils.checkAccountName( agent.getRealName() ) ) {
				addActionError("名称格式不正确，只能输入中英文，数字，括号和空格!");
				return ERROR;
			}
			String agentType = ""; 
			String agentNumber = agent.getOrganizationCode();
			Map<String, String> agentNumberMap = AgentNumberType.getAllEnumMap();
			if ( null !=  agentNumberMap.get(agent.getCompanyid()) ) {
				agentType = agentNumberMap.get(agent.getCompanyid()) ;
			} else {
				agentType = Constant.OTHER_AGENTNUMBER ;
			}
			
			// 判断录入的序号编码是否已存在
			boolean isExist = powerInfoService.queryOperatorInfoByNumberCode(agentType , agentNumber);
			if ( null == agent.getOrganizationCode() || "".equals(agent.getOrganizationCode().trim()) 
					|| ( true == isExist) ){
				addActionError("序号编码不能为空或者序号编码已存在，请重新输入!");
				return ERROR;
			}
			// 设置 序号编码  分公司编码+数字   例如：0_01,1_00001
			agent.setOrganizationCode(agentType + agentNumber);
			
			String isUseDefModule = agent.getIsUseDefModule();
			if(null != isUseDefModule && !isUseDefModule.equals("")){
				// 查询当前默认的模板信息
				ProfitModule bean = modelService.queryDefProfitModuleByAgentId( logingOperators.getId());

				// 如果查询模板id为空,返回异常
				if(null == bean){
					addActionError("代理申请失败,默认分润模板不存在,请重新添加或设置默认模板!");
					return ERROR;
				}
			}
		//	agent.setSuperiorId(logingOperators.getId());
			agent.setSuperiorId(Long.valueOf(agent.getCompanyid()));
			agent.setOperators(logingOperators.getAccountNo());
			if(agent.getRoleType().equals(Role.O_MANAGER.getCode())){
				agent.setFlag(Constance.OPERATORS_FLAG_OEM);//O单标志
			}else{
				agent.setFlag(logingOperators.getFlag());
			}
			if(Role.RISK_CONTROL_LEAD.getCode().equals(agent.getRoleType()) || Role.RISK_CONTROL_OPERATORS.getCode().equals(agent.getRoleType())){
			    agent.setAgentType("1");
                        }else{
                            agent.setAgentType("0");
                        }
			Date date=new Date();
			agent.setValidStartDate(DateUtil.initStartDate(date));
			agent.setValidEndDate(DateUtil.initEndDate());

			pwd = agentService.isAddOneAgent(agent,logingOperators.getAccountNo(),logingOperators);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage(),e);
			addActionError("保存代理商信息出错,请联系管理员");
			return ERROR;
		}
		 getRequest().setAttribute("msg", "代理商["+agent.getAccountNo()+"]录入成功,初始密码" + pwd);
		return SUCCESS;
	}
	//初始化加载页面
	@Action(value = "oneAgentJsp", results = {
			@Result(name = "success", location = "/pages/agent/addOneAgent.jsp"),
			@Result(name = "error", location = "/error.jsp") }
	)
	public String  oneAgentJsp(){
		List orgList=new ArrayList();
		try {
			Operators logingOperators=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
			
			String loginId = String.valueOf(logingOperators.getId());
			// 如果登陆账号不是系统管理员以及收单事业部
			if( !logingOperators.getRoleType().equals(Role.SYSTEM.getCode())
					 && !loginId.equals(Constant.SHOUDANSHIYEBU_ID)){
				addActionError("此登陆账号没有权限");
				return ERROR;
			}

			// 取收单事业部下各个区域信息
			List<Operators> companyList = merchantServices.queryLowOneAgent(Constant.SHOUDANSHIYEBU_ID);
			getRequest().setAttribute("companyList",companyList );
			
			//orgList=orgService.listOrgs(logingOperators);
			orgList = orgService.queryOrgList();
			getRequest().setAttribute("op",logingOperators );

			Map<String, String> mccMap = agentService.getMccArray4Agent(logingOperators.getAccountNo(),logingOperators.getRoleType());
			
			getRequest().setAttribute("mccList",mccMap);//mcc
			getRequest().setAttribute("perList",getDefPer());//
			
			Map<String, String> map=dealAgentType(logingOperators.getFlag(), logingOperators.getAgentType(), ConfigProperties.getAgentTypeProperties());
			getRequest().setAttribute("agTypeList",map);

			// 查询当前默认的模板信息
			ProfitModule bean = modelService.queryDefProfitModuleByAgentId(logingOperators.getId());
			int moduleSize = 0;
			if(null != bean){
				moduleSize = 1;
			}
			getRequest().setAttribute("moduleSize", moduleSize);
			
			getRequest().setAttribute("orgList", orgList);
			getRequest().setAttribute("areaList", ConfigProperties.getAreaCodeProperties());
			getRequest().setAttribute("merberFlagMap", MerberFlag.getAllEnumMap());
			getRequest().setAttribute("invoiceRateMap", InvoiceRateType.getAllEnumMap()); // 发票扣率Map
			
		} catch (Exception e) {
			// TODO: handle exception
			logger.error(e.getMessage(),e);
			addActionError("加载代理商基本信息出错！！");
		}
		return SUCCESS;
	}
	
	
	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		// TODO Auto-generated method stub
		
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	protected String getInitPageSize() {
		// TODO Auto-generated method stub
		return null;
	}

	public Operators getAgent() {
		return agent;
	}

	public void setAgent(Operators agent) {
		this.agent = agent;
	}
	public List<ProfitPercent> getProfitPerList() {
		return profitPerList;
	}
	public void setProfitPerList(List<ProfitPercent> profitPerList) {
		this.profitPerList = profitPerList;
	}
	
	public HashMap<String,String> getDefPer(){
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("01", "01");
		map.put("02", "02");
		map.put("03", "03");
		map.put("04", "04");
		return map;
	}
	@Action(value="validateAccountNo")
	public void vilidateAccountNo()
	{
		HttpServletResponse response=ServletActionContext.getResponse();
		response.setContentType("text/html;charset=UTF-8");
		boolean value=true;
		try {
			agent=operatorService.validateAccount(agent.getAccountNo());
			if(agent!=null)
			{
				value=false;
			}
			response.getWriter().print(value);
		} catch (ServiceException e) {
			logger.error(e.getMessage(),e);
			addActionError("验证登陆账号错误!!!");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
